package cn.wolfcode.p2p.controller;

import cn.wolfcode.p2p.base.domain.LoginInfo;
import cn.wolfcode.p2p.base.exception.DisplayableException;
import cn.wolfcode.p2p.base.service.ILoginInfoService;
import cn.wolfcode.p2p.base.util.AjaxResult;
import cn.wolfcode.p2p.base.util.MD5;
import cn.wolfcode.p2p.base.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController {

    @Autowired
    private ILoginInfoService loginInfoService;

    @RequestMapping("/userLogin")
    @ResponseBody
    public AjaxResult userLogin(String username, String password) {
        AjaxResult result = null;
        try {
            LoginInfo loginInfo = loginInfoService.login(username, MD5.encoder(password), LoginInfo.USERTYPE_NOMAL);
            //传进来的密码需要加密后拿到和数据库对比
            if (loginInfo.getMissNumber() > 0) {
                result = new AjaxResult(false, "您已输错密码第" + loginInfo.getMissNumber() + "次,还剩余" + (3 - loginInfo.getMissNumber()) + "次机会");
                if (loginInfo.getMissNumber() > 3) {
                    result = new AjaxResult(false, "您的账户已被冻结,冻结时间为一个小时");
                }
                return result;
            }
            //如果loginInfo 为null的话
            if (loginInfo == null) {
                result = new AjaxResult(false, "账号或者密码错误,请重新输入");
                return result;
            }
            result = new AjaxResult("登陆成功");
        } catch (DisplayableException e) {
            e.printStackTrace();
            //如果底层是抛出这个异常的话 则把 异常信息显示给用户看
            result = new AjaxResult(false, e.getMessage());
        } catch (NullPointerException er) {
            er.printStackTrace();
            //如果底层是抛出这个异常的话 则把 异常信息显示给用户看
            result = new AjaxResult(false, "您的账户已被冻结,冻结时间为一个小时");
        } catch (Exception ex) {
            ex.printStackTrace();
            //把异常信息写入到日志中
            result = new AjaxResult(false, "系统异常,程序员哥哥正在努力抢救中...");
        }
        return result;
    }
}
